<?php
namespace api\user\controller;

use api\user\model\SignModel;
use api\common\controller\RestUserBaseController;
use think\Db;

class SignController extends RestUserBaseController
{
    protected $userId;

    public function __construct()
    {
        parent::__construct();
        $this->userId = $this->getUserId();
    }


    public function index()
    {
        $total_sign =  Db::name('sign')->where('user_id',$this->userId)->count();
        $data = Db::name('sign')->where('user_id',$this->userId)->whereTime('createtime', 'w')->order('createtime asc')->select(); 
        $this->success('请求成功', ['total_sign'=>$total_sign,'list' => $data]);
    }


    public function save()
    {
        $file = fopen("./lock.txt","r");
        if(flock($file,LOCK_EX)){
            $SignModel = new SignModel();
            if(!$SignModel->checkSign($this->userId)){
                $this->error('你今天已经签到过了');
            }
            $sign_reward = 0.6;
            //奖励要获取
            $count = $SignModel->where('user_id',$this->userId)->lock(true)->count();
            if($count >=30){
                $count = $count%30;
            }
            $money = Db::name('sign_set')->where('day',$count + 1)->value('money');
            if(!empty($money)){
                $sign_reward = $money;
            }
            $sign['user_id']      = $this->userId;
            $sign['sign_reward']  = $sign_reward;
            $sign['createtime']   = date("Y-m-d");

            //资金明细
            $user_balance_log['user_id']    = $this->userId;
            $user_balance_log['amount']     = $sign_reward;
            $user_balance_log['before']     = $this->user['mission_wallet'];
            $user_balance_log['after']      = $this->user['mission_wallet']+$sign_reward;
            $user_balance_log['remark']     = '签到奖励';
            $user_balance_log['type']       = 1;
            $user_balance_log['log_type']   = 2;
            $user_balance_log['createtime'] = time();
            // 启动事务
            Db::startTrans();
            try{
                Db::name('sign')->insert($sign);
                Db::name('user_balance_log')->insert($user_balance_log);
                Db::name('user')->where('id',$this->userId)->update(['mission_wallet' => Db::raw('mission_wallet+' . ($sign_reward))]);
                Db::name('user_task')->insert(['task_id'=>10,'user_id'=>$this->userId,'createtime'=>date('Y-m-d')]);
                // 提交事务
                Db::commit();
                $this->success('签到成功',['amount'=>$sign_reward]);
            } catch (\think\Exception\DbException $exception){
                // 回滚事务
                Db::rollback();
                $this->error('签到失败');
            }
            flock($file,LOCK_UN);
        }
        fclose($file);
    }

}
